<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片水印工具</title>
    <style>
        body {
            font-family: sans-serif;
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            padding-right: 100px;
            box-sizing: border-box;
        }
        
        .main-content {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .control-panel {
            flex: 1;
            min-width: 300px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .preview-panel {
            flex: 2;
            min-width: 300px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .button-panel {
            position: fixed;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            width: 100px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        
        input, select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 14px;
        }
        
        #watermarkPreset {
            font-size: 13px;
        }
        
        button {
            background-color: #4CAF50;
            color: white;
            padding: 12px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        #originalImage {
            max-width: 100%;
            margin: 10px 0;
            border: 1px solid #eee;
            background-color: #f9f9f9;
            padding: 20px;
            box-sizing: border-box;
            object-fit: contain;
        }
        
        .save-btn {
            background-color: #2196F3;
        }
        
        .save-btn:hover {
            background-color: #0b7dda;
        }
        
        .remove-btn {
            background-color: #f44336;
        }
        
        .remove-btn:hover {
            background-color: #d32f2f;
        }
        
        .reset-btn {
            background-color: #ff9800;
        }
        
        .reset-btn:hover {
            background-color: #e68900;
        }
        
        .status-message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        
        .success {
            background-color: #dff0d8;
            color: #3c763d;
            display: block;
        }
        
        .error {
            background-color: #f2dede;
            color: #a94442;
            display: block;
        }
        
        .size-controls {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .size-controls input {
            flex: 1;
        }
        
        .size-controls button {
            width: auto;
            padding: 5px 10px;
            font-size: 14px;
        }
        
        @media (max-width: 992px) {
            body {
                padding-right: 20px;
            }
            
            .button-panel {
                position: static;
                transform: none;
                width: 100%;
                margin-top: 20px;
            }
            
            .main-content {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="main-content">
        <div class="control-panel">
            <div class="form-group">
                <label for="imageUpload">选择图片</label>
                <input type="file" id="imageUpload" accept="image/*">
                <small style="color: #666; margin-top: 5px; display: block;">支持JPG、PNG等常见图片格式</small>
            </div>
            
            <div class="form-group">
                <label for="watermarkPreset">预设水印</label>
                <select id="watermarkPreset">
                    <option value="">-- 选择预设水印 --</option>
                    <option value="银行">银行：仅供XX银行开户办卡使用，X年X月X日前有效，过期和其他用途无效</option>
                    <option value="入职">入职：仅供XX公司X年X月X日入职使用</option>
                    <option value="租房">租房：X年X月X日办理XX房屋租赁专用</option>
                    <option value="社保">社保：XX市社保局业务受理专用</option>
                    <option value="公积金">公积金提取：仅供公积金提取使用，X年X月X日前有效，过期无效</option>
                    <option value="手机号">手机号：中国移动办理手机号开通业务专用，其他用途无效</option>
                    <option value="网络提交">网络提交：仅限XX平台实名认证使用</option>
                    <option value="房产">买房/卖房：仅供XX小区房产过户使用有效期至X年X月X日；XX不动产登记中心备案，再复印无效</option>
                    <option value="车辆">车辆过户：仅限XX车牌号过户使用有效期至X年X月X日；XX车管所备案专用，再复印无效</option>
                    <option value="学历认证">学历认证：仅限XX机构学历验证使用，有效期X天</option>
                    <option value="签证申请">签证申请：仅用于XX国签证办理，复印无效</option>
                    <option value="医疗证明">医疗证明：XX医院出具，仅供XX用途使用</option>
                    <option value="工作证明">工作证明：仅限证明在职情况，不作其他用途</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="watermarkText">水印文本</label>
                <input type="text" id="watermarkText" placeholder="输入水印文本" value="">
            </div>
            
            <div class="form-group">
                <label for="watermarkColor">水印颜色</label>
                <input type="color" id="watermarkColor" value="#ff0000">
            </div>
            
            <div class="form-group">
                <label for="watermarkOpacity">水印透明度</label>
                <input type="range" id="watermarkOpacity" min="0" max="100" value="50">
                <span id="opacityValue">50%</span>
            </div>
            
            <div class="form-group">
                <label for="watermarkScale">水印比例(%)</label>
                <div class="size-controls">
                    <button type="button" id="decreaseScale">-</button>
                    <input type="number" id="watermarkScale" min="1" max="20" value="5">
                    <button type="button" id="increaseScale">+</button>
                </div>
            </div>
            
            <div class="form-group">
                <label for="watermarkRotate">旋转角度(度)</label>
                <input type="number" id="watermarkRotate" min="-180" max="180" value="-15">
            </div>
            
            <div class="form-group">
                <label for="watermarkPosition">水印位置</label>
                <select id="watermarkPosition">
                    <option value="tiled">平铺</option>
                    <option value="top-left">左上角</option>
                    <option value="top-right">右上角</option>
                    <option value="bottom-left">左下角</option>
                    <option value="bottom-right">右下角</option>
                    <option value="center" selected>居中</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="watermarkFont">水印字体</label>
                <select id="watermarkFont">
                    <option value="'SimSun', serif">宋体</option>
                    <option value="'SimHei', sans-serif">黑体</option>
                    <option value="'KaiTi', serif">楷体</option>
                </select>
            </div>
            
            <div class="status-message" id="statusMessage"></div>
        </div>
        
        <div class="preview-panel">
            <h3>图片预览（含水印）</h3>
            <div class="image-container">
                <img id="originalImage" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='200' viewBox='0 0 300 200'%3E%3Crect width='300' height='200' fill='%23f9f9f9'/%3E%3Ctext x='50%25' y='50%25' dominant-baseline='middle' text-anchor='middle' fill='%23ccc' font-size='14'%3E请选择图片%3C/text%3E%3C/svg%3E" alt="图片预览">
            </div>
        </div>
    </div>
    
    <div class="button-panel">
        <button id="saveImage" class="save-btn" disabled>保存图片</button>
        <button id="removeImage" class="remove-btn">清除图片</button>
        <button id="resetSettings" class="reset-btn">重置设置</button>
    </div>

    <script>
        const imageUpload = document.getElementById('imageUpload');
        const originalImage = document.getElementById('originalImage');
        const watermarkPreset = document.getElementById('watermarkPreset');
        const watermarkText = document.getElementById('watermarkText');
        const watermarkColor = document.getElementById('watermarkColor');
        const watermarkOpacity = document.getElementById('watermarkOpacity');
        const opacityValue = document.getElementById('opacityValue');
        const watermarkScale = document.getElementById('watermarkScale');
        const decreaseScaleBtn = document.getElementById('decreaseScale');
        const increaseScaleBtn = document.getElementById('increaseScale');
        const watermarkRotate = document.getElementById('watermarkRotate');
        const watermarkPosition = document.getElementById('watermarkPosition');
        const watermarkFont = document.getElementById('watermarkFont');
        const saveImageBtn = document.getElementById('saveImage');
        const removeImageBtn = document.getElementById('removeImage');
        const resetSettingsBtn = document.getElementById('resetSettings');
        const statusMessage = document.getElementById('statusMessage');
        
        const MAX_PREVIEW_WIDTH = 800;
        const MAX_PREVIEW_HEIGHT = 600;
        const defaultOriginalImage = originalImage.src;
        let originalImageData = null;
        let previewImageData = null;
        
        const initialSettings = {
            text: watermarkText.value,
            color: watermarkColor.value,
            opacity: watermarkOpacity.value,
            scale: watermarkScale.value,
            rotate: watermarkRotate.value,
            position: watermarkPosition.value,
            font: watermarkFont.value,
            preset: watermarkPreset.value
        };
        
        function calculateWatermarkSize(image) {
            const imageWidth = image.naturalWidth || image.offsetWidth;
            return Math.max(10, Math.round(imageWidth * (parseInt(watermarkScale.value) / 100)));
        }
        
        function showMessage(text, isError = false) {
            statusMessage.textContent = text;
            statusMessage.className = 'status-message';
            statusMessage.classList.add(isError ? 'error' : 'success');
            setTimeout(() => { statusMessage.className = 'status-message'; }, 3000);
        }
        
        function throttle(fn, delay = 100) {
            let lastTime = 0;
            return function(...args) {
                const now = Date.now();
                if (now - lastTime >= delay) {
                    fn.apply(this, args);
                    lastTime = now;
                }
            };
        }
        
        // 核心修改：使用Promise确保水印绘制完成后再返回结果
        function addWatermark(isPreview = true) {
            return new Promise((resolve) => {
                if (originalImage.src === defaultOriginalImage || !originalImageData) {
                    resolve(null);
                    return;
                }
                const watermarkTextVal = watermarkText.value.trim();
                if (!watermarkTextVal) {
                    showMessage('请输入水印文本', true);
                    resolve(null);
                    return;
                }

                let canvasWidth, canvasHeight, baseData;
                if (isPreview) {
                    canvasWidth = originalImage.offsetWidth;
                    canvasHeight = originalImage.offsetHeight;
                    baseData = previewImageData;
                } else {
                    canvasWidth = parseInt(originalImage.dataset.originalWidth);
                    canvasHeight = parseInt(originalImage.dataset.originalHeight);
                    baseData = originalImageData;
                }

                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                canvas.width = canvasWidth;
                canvas.height = canvasHeight;

                const baseImg = new Image();
                baseImg.crossOrigin = 'anonymous';
                baseImg.onload = function() {
                    ctx.drawImage(baseImg, 0, 0, canvasWidth, canvasHeight);

                    const watermarkSize = calculateWatermarkSize(baseImg);
                    const alphaHex = Math.round(watermarkOpacity.value / 100 * 255)
                        .toString(16)
                        .padStart(2, '0');
                    ctx.fillStyle = `${watermarkColor.value}${alphaHex}`;
                    ctx.font = `${watermarkSize}px ${watermarkFont.value}`;
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    const text = watermarkTextVal;
                    const rotateRad = watermarkRotate.value * Math.PI / 180;
                    const position = watermarkPosition.value;

                    if (position === 'tiled') {
                        const textLength = text.length;
                        const tileSize = watermarkSize * (textLength > 20 ? 5 : 4);
                        ctx.save();
                        ctx.rotate(rotateRad);
                        const rotatedWidth = canvas.width * Math.cos(rotateRad) + canvas.height * Math.sin(rotateRad);
                        const rotatedHeight = canvas.width * Math.sin(rotateRad) + canvas.height * Math.cos(rotateRad);
                        for (let y = -tileSize; y < rotatedHeight + tileSize; y += tileSize) {
                            for (let x = -tileSize; x < rotatedWidth + tileSize; x += tileSize) {
                                ctx.fillText(text, x, y);
                            }
                        }
                        ctx.restore();
                    } else {
                        let x, y;
                        const textMetrics = ctx.measureText(text);
                        const textWidth = textMetrics.width;
                        const textHeight = watermarkSize;
                        
                        switch(position) {
                            case 'top-left': x = textWidth/2 +10; y = textHeight/2 +10; break;
                            case 'top-right': x = canvas.width - textWidth/2 -10; y = textHeight/2 +10; break;
                            case 'bottom-left': x = textWidth/2 +10; y = canvas.height - textHeight/2 -10; break;
                            case 'bottom-right': x = canvas.width - textWidth/2 -10; y = canvas.height - textHeight/2 -10; break;
                            case 'center': x = canvas.width/2; y = canvas.height/2; break;
                        }
                        
                        ctx.save();
                        ctx.translate(x, y);
                        ctx.rotate(rotateRad);
                        ctx.fillText(text, 0, 0);
                        ctx.restore();
                    }

                    const result = canvas.toDataURL('image/png');
                    if (isPreview) {
                        originalImage.src = result;
                        saveImageBtn.disabled = false;
                    }
                    resolve(result); // 确保绘制完成后再返回
                };

                baseImg.src = baseData;
            });
        }
        
        const throttledAddWatermark = throttle(() => addWatermark(true), 100);
        
        watermarkPreset.addEventListener('change', function() {
            if (this.value) {
                watermarkText.value = this.options[this.selectedIndex].text;
                const textLength = watermarkText.value.length;
                if (textLength > 30) watermarkScale.value = Math.max(1, 5 - Math.floor(textLength / 10));
                else if (textLength > 20) watermarkScale.value = 4;
                addWatermark();
            }
        });
        
        decreaseScaleBtn.addEventListener('click', function() {
            const currentScale = parseInt(watermarkScale.value);
            if (currentScale > parseInt(watermarkScale.min)) {
                watermarkScale.value = currentScale - 1;
                addWatermark();
            }
        });
        
        increaseScaleBtn.addEventListener('click', function() {
            const currentScale = parseInt(watermarkScale.value);
            if (currentScale < parseInt(watermarkScale.max)) {
                watermarkScale.value = currentScale + 1;
                addWatermark();
            }
        });
        
        watermarkOpacity.addEventListener('input', function() {
            opacityValue.textContent = this.value + '%';
            throttledAddWatermark();
        });
        
        imageUpload.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            if (!file.type.startsWith('image/')) {
                showMessage('请选择图片文件', true);
                return;
            }
            const reader = new FileReader();
            reader.onload = function(event) {
                originalImageData = event.target.result;
                const tempImg = new Image();
                tempImg.onload = function() {
                    let previewWidth = tempImg.width;
                    let previewHeight = tempImg.height;
                    if (previewWidth > MAX_PREVIEW_WIDTH) {
                        const scale = MAX_PREVIEW_WIDTH / previewWidth;
                        previewWidth *= scale;
                        previewHeight *= scale;
                    }
                    if (previewHeight > MAX_PREVIEW_HEIGHT) {
                        const scale = MAX_PREVIEW_HEIGHT / previewHeight;
                        previewWidth *= scale;
                        previewHeight *= scale;
                    }
                    const previewCanvas = document.createElement('canvas');
                    previewCanvas.width = previewWidth;
                    previewCanvas.height = previewHeight;
                    previewCanvas.getContext('2d').drawImage(tempImg, 0, 0, previewWidth, previewHeight);
                    previewImageData = previewCanvas.toDataURL('image/png');
                    originalImage.dataset.originalWidth = tempImg.width;
                    originalImage.dataset.originalHeight = tempImg.height;
                    originalImage.src = previewImageData;
                    saveImageBtn.disabled = true;
                    addWatermark(true);
                    showMessage('图片加载成功，已自动添加水印');
                };
                tempImg.src = originalImageData;
            };
            reader.readAsDataURL(file);
        });
        
        watermarkText.addEventListener('input', throttledAddWatermark);
        watermarkColor.addEventListener('input', () => addWatermark());
        watermarkScale.addEventListener('input', throttledAddWatermark);
        watermarkRotate.addEventListener('input', throttledAddWatermark);
        watermarkPosition.addEventListener('change', () => addWatermark());
        watermarkFont.addEventListener('change', () => addWatermark());
        
        // 保存逻辑修改：使用async/await确保水印绘制完成
        saveImageBtn.addEventListener('click', async function() {
            if (originalImage.src === defaultOriginalImage || !originalImageData) return;
            try {
                const watermarkedDataUrl = await addWatermark(false); // 等待绘制完成
                if (watermarkedDataUrl) {
                    const link = document.createElement('a');
                    link.download = `watermarked-image-${Date.now()}.png`;
                    link.href = watermarkedDataUrl;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    showMessage('图片保存成功，已包含水印');
                }
            } catch (error) {
                showMessage('保存失败，请重试', true);
            }
        });
        
        removeImageBtn.addEventListener('click', function() {
            originalImage.src = defaultOriginalImage;
            originalImageData = null;
            previewImageData = null;
            imageUpload.value = '';
            saveImageBtn.disabled = true;
            showMessage('图片已清除');
        });
        
        resetSettingsBtn.addEventListener('click', function() {
            watermarkPreset.value = initialSettings.preset;
            watermarkText.value = initialSettings.text;
            watermarkColor.value = initialSettings.color;
            watermarkOpacity.value = initialSettings.opacity;
            opacityValue.textContent = initialSettings.opacity + '%';
            watermarkScale.value = initialSettings.scale;
            watermarkRotate.value = initialSettings.rotate;
            watermarkPosition.value = initialSettings.position;
            watermarkFont.value = initialSettings.font;
            if (originalImageData) addWatermark();
            showMessage('设置已重置，已更新水印');
        });
    </script>
</body>
</html>